package initial

import (
	"flag"
	"fmt"
	"gitee.com/xianglinzeng/gwayne/pkg/config"
	"k8s.io/klog/v2"
	"os"
	"path/filepath"
)

func InitKlog() {

	logDir := getLogDir(config.Conf.Log.LogPath)
	if err := ensureLogDirExists(logDir); err != nil {
		klog.Fatalf("日志目录不存在: %v", err)
	}

	var fs flag.FlagSet
	klog.InitFlags(&fs)

	switch config.Conf.App.RunMode {
	case "debug":
		// debug 模式下日志输出到终端和日志文件
		fs.Set("logtostderr", "false")
		fs.Set("alsologtostderr", "true")
		fs.Set("log_file_max_size", "10000")
		fs.Set("log_file", config.Conf.Log.LogPath)

	case "release":
		// 将日志输出到文件
		fs.Set("logtostderr", "false")
		fs.Set("log_file_max_size", "10000")
		fs.Set("log_file", config.Conf.Log.LogPath)
	default:
		klog.SetOutput(os.Stdout)
	}

	flag.Parse()
	klog.Info("日志初始化完成。")
}

func openLogFile(logFilePath string) *os.File {
	logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
	if err != nil {
		klog.Fatalf("打开日志文件出错: %v", err)
	}
	return logFile
}

func ensureLogDirExists(logFile string) error {
	dir := filepath.Dir(logFile)

	if _, err := os.Stat(dir); os.IsNotExist(err) {
		if err := os.MkdirAll(dir, 0755); err != nil {
			return fmt.Errorf("创建日志目录出错 %s: %v", dir, err)
		}
	}
	return nil
}

// getLogDir extracts the directory part from the log file path
func getLogDir(logFilePath string) string {
	// Use filepath.Dir to get the directory from the full log file path
	return filepath.Dir(logFilePath)
}
